package cn.tedu.ivos.vehicle.service.impl;

import cn.tedu.ivos.vehicle.mapper.VehicleMapper;
import cn.tedu.ivos.vehicle.pojo.dto.SaveVehicleParam;
import cn.tedu.ivos.vehicle.pojo.dto.VehicleQuery;
import cn.tedu.ivos.vehicle.pojo.entity.Vehicle;
import cn.tedu.ivos.vehicle.pojo.vo.VehicleVO;
import cn.tedu.ivos.vehicle.service.VehicleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class VehicleServiceImpl implements VehicleService {
    @Autowired
    VehicleMapper vehicleMapper;

    @Override
    public List<VehicleVO> selectVehicle(VehicleQuery vehicleQuery) {
        log.debug("查询车辆业务参数：{}", vehicleQuery);
        List<VehicleVO> list = vehicleMapper.selectVehicle(vehicleQuery);
        return list;
    }

    @Override
    public void saveVehicle(SaveVehicleParam param) {
        log.debug("添加车辆业务参数：{}", param);
        VehicleVO vehicleVO = vehicleMapper.selectByLicense(param.getLicense());
        Vehicle vehicle = new Vehicle();
        BeanUtils.copyProperties(param, vehicle);
        if (param.getId() == null){
            if (vehicleVO != null){
                throw new RuntimeException("车辆已存在");
            }
        vehicle.setCreateTime(new Date());
        vehicle.setStatus("1");
        vehicle.setGeofenceBindStatus("0");
        vehicle.setGeofenceId( null);
        vehicleMapper.insertVehicle(vehicle);
        }else {
            if (vehicleVO != null && !vehicleVO.getId().equals(param.getId())){
                throw new RuntimeException("车辆已存在");
            }
            vehicle.setUpdateTime(new Date());
            vehicleMapper.updateVehicle(vehicle);

        }


    }

    @Override
    public void deleteVehicleId(Long id) {
        log.debug("删除车辆：id="+id);
        vehicleMapper.deleteVehicleId(id);
    }

    @Override
    public void unbindVehicleId(Long id) {
        log.debug("解绑车辆编号"+id);
        Vehicle vehicle =new Vehicle();
        vehicle.setId(id);
        vehicle.setGeofenceBindStatus("0");
        vehicle.setGeofenceId(null);
        vehicle.setUpdateTime(new Date());
        vehicleMapper.unbindNullVehicle(vehicle);
    }

    @Override
    public void bindVehicleId(Long geofenceId, Long vehicleId) {
        log.debug("围栏Id:"+geofenceId+",车辆Id:"+vehicleId);
        Vehicle vehicle = new Vehicle();
        vehicle.setId(vehicleId);
        vehicle.setGeofenceId(geofenceId);
        vehicle.setGeofenceBindStatus("1");
        vehicle.setUpdateTime(new Date());
        vehicleMapper.updateVehicle(vehicle);
    }
}